<?php

namespace App\Services\Easywechat;

/**
 * 微信小程序开发组
 * class MiniAppService
 */
class EasyModule
{
    protected string $message = '';
    protected array  $data    = [];
    protected int    $ttl     = 1 * 24 * 60 * 60;

    public function __construct() {}

    /**
     * 统一校验 返回
     * @param $response
     * @return bool
     */
    protected function response($response): bool
    {
        if ($response->isFailed()) {
            return $this->error($response->getContent());
        }

        return $this->success($response->getContent());
    }

    /**
     * 返回成功结果
     * @param string $response
     * @return bool
     */
    protected function success(string $response): bool
    {
        $this->set($response);
        return true;
    }

    /**
     * 返回失败结果
     * @param string $response
     * @return false
     */
    protected function error(string $response): bool
    {
        $this->set($response);
        return false;
    }

    /**
     * 存入结果
     * @param string $response
     * @return bool
     */
    protected function set(string $response): bool
    {
        $this->data = $this->json($response);

        if (!empty($this->data['errmsg'])) {
            $this->message = $this->data['errmsg'];
        } elseif (!empty($this->data['message'])) {
            $this->message = $this->data['message'];
        } else {
            $this->message = 'EasyModule控件有误，请输出response';
        }

        return true;
    }

    /**
     * 解析数据
     * @param string $response
     * @return mixed
     */
    protected function json(string $response): mixed
    {
        return json_decode($response, true);
    }

    /**
     * 获取成功数据
     * @return array
     */
    public function get(): array
    {
        return $this->data;
    }

    /**
     * 获取消息
     * @return string
     */
    public function getMessage(): string
    {
        return $this->message;
    }
}